<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>友人聊天室</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
  <link rel="stylesheet" href="../static/css/me.css" th:href="@{/css/me.css}">
  <link rel="stylesheet" href="../static/css/friends_record.css" th:href="@{/css/friends_record.css}">
  <style>
      .delete-button {
          height: 20px;
          border-radius: 50%;
          background-color: #c66675;
          color: #fff;
          font-size: 16px;
          text-align: center;
          line-height: 20px;
          cursor: pointer;
          opacity: 0.8;
          width: 60%;
          margin: auto;
          margin-top: 5px;
      }
  </style>
</head>
<body class="friendBody">

<!--导航-->
<nav class="gird-header">
  <div class="ui container" style="width: 95%!important;"> <!-- 加一个容器 -->
    <div class="ui inverted secondary stackable menu"> <!-- 菜单 stackable:可堆叠的,表示屏幕小时自动堆叠-->
      <a th:href="@{/user_index}"><h2 class="ui white header item">GuideSystem</h2></a> <!-- 蓝绿色标题 -->
      <a href="#" th:href="@{/user_index}" class="m-item m-mobile-hide item"><i class="home icon"></i>首页</a>
      <!-- icon表示图标 -->
      <a href="#" th:href="@{/user_forum}" class="m-item m-mobile-hide item"><i class="comments icon"></i>论坛</a>
      <a href="#" th:href="@{/user_types/-1}" class="m-item m-mobile-hide item"><i class="idea icon"></i>分类</a>
      <a href="#" th:href="@{/about}" class="m-item m-mobile-hide item"><i class="info icon"></i>我的</a>
      <div class="m-top-right m-mobile-hide item m-item" style="margin: auto; margin-top: -5px;"> <!-- 靠右 -->
        <form name="search" method="get" action="#" th:action="@{/user_search}" target="_blank">
          <div class="ui icon input">
            <input type="text" name="query" placeholder="Search..." th:value="${query}">
            <i onclick="document.forms['search'].submit()" class="search link icon"></i>
          </div>
        </form>
        <div class="ui dropdown item">
          <div class="container">
            <img src="../static/images/店铺1.jpg" th:src="@{${session.user?.avatar}}" alt="" class="ui avatar image"
                 style="object-fit: cover;
                       outline: 0px;
                       background-size: 100% 100%;">
          </div>
          <i class="dropdown icon"></i>
          <div class="menu">
            <a href="#" th:href="@{/about}" target="_blank" class="item">我的</a>
            <a href="#" th:href="@{/edit/password}" class="item">修改密码</a>
            <a href="#" th:href="@{/login/exit}" id="logout-link" class="item">退出</a>
            <a href="#" onclick="deleteAccount()" class="item">注销</a> <!--得更新-->
          </div>
          <input type="hidden" name="concurrentUsername" th:value="${session.user?.username}"/>
        </div>
      </div>
    </div>
  </div>
  <a href="#" class="ui menu toggle black button icon m-top-right m-mobile-show">
    <i class="sidebar icon"></i>
  </a>
</nav>

<!--顶部图片-->
<div class="m-bg-type_outer" style="width: 100%; height: 35%">
  <img src="../static/images/friendsbg.jpg" th:src="@{/images/friendsbg.jpg}" alt="" class="ui m-bg image"
       style="width: 100%; opacity: 0.7">
  <div class="m-bg-class_cover">
    <div align="center">
      <div class="ui container" align="center" style="position: relative ;bottom: -540px;">
        <div class="m-font-size-title " align="center" style="font-family:'STXingkai'">友人聊天室</div>
        <div class="m-font-size-text-init-title m-margin-top" align="center">
          转瞬即逝的相逢与离别，每一个瞬间，我都想要珍惜
        </div>
      </div>
    </div>
  </div>
</div>

<!--中间内容-->
<div class="m-margin- animated animate__fadeIn" id="app">
  <div class="ui m-opacity container">
    <div class="box-shadow-max">
      <div class="" style="font-size: 35px;font-weight: bold" align="center" v-if="isShowChat">
        好友：<a v-bind:href="'/dev/userOtherAbout/' + toId" target="_blank">{{toNickname}}</a>
        <!--<span style="font-size: 28px; font-weight: lighter" v-if="isOnline">(在线)</span>
        <span style="font-size: 28px; font-weight: lighter" v-else>(离线)</span>-->
      </div>
      <div class="ui m-container-mm segment m-padded-tb-large m-opacity"
           style="position: relative; height: 56em !important; overflow-y: scroll;">

        <!-- 聊天记录区域 -->
        <div class="ui m-container m-margin-top-large" style="min-height: 545px !important;">
          <div class="ui divided items chat-history" v-for="message in historyMessage">
            <!-- 我的消息 -->
            <div class="item right aligned reply" v-if="message.toName">
              <div class="content">
                <img class="ui circular image avatar me" src="../static/images/friend_record_3.jpg"
                     th:src="@{${session.user?.avatar}}" alt="My Avatar"
                     style="object-fit: cover;
                       cursor: pointer;
                       outline: 0px;
                       background-size: 100% 100%;">
                <div class="bubble me">
                  <p style="font-weight: bold">{{message.message}}</p>
                  <div class="meta">
                    <span class="date">{{message.sendTime}}</span>
                  </div>
                </div>
              </div>
            </div>
            <!--对面消息-->
            <div class="item left aligned" v-else>
              <img class="ui circular image avatar ta" :src="toAvatar"
                   alt="Kafka's Avatar"
                   style="object-fit: cover;
                     cursor: pointer;
                     outline: 0px;
                     background-size: 100% 100%;">
              <div class="content">
                <div class="bubble ta">
                  <p style="font-weight: bold">{{message.message}}</p>
                  <div class="meta">
                    <span>{{message.sendTime}}</span>
                  </div>
                </div>
              </div>
            </div>
            <!--/*-->
            <div class="item right aligned reply">
              <div class="content">
                <a><img class="ui circular image avatar me" src="../static/images/friend_record_3.jpg" alt="My Avatar"></a>
                <div class="bubble me">
                  <p>你好，Kafka！这是你的回复。</p>
                  <div class="meta">
                    <span class="date">今天 10:00</span>
                  </div>
                </div>
              </div>
            </div>
            <div class="item right aligned reply">
              <div class="content">
                <img class="ui circular image avatar me" src="../static/images/friend_record_3.jpg" alt="My Avatar">
                <div class="bubble me">
                  <p>你好，Kafka！这是你的回复。</p>
                  <div class="meta">
                    <span class="date">今天 10:00</span>
                  </div>
                </div>
              </div>
            </div>
            <!--*/-->
            <!-- 更多聊天记录... -->
          </div>
        </div>

        <!-- 输入与发送消息区域 -->
        <div class="ui form message-input-area" v-if="chatMes">
          <div class="field">
            <textarea rows="2" placeholder="在此输入您的消息..." @keyup.enter="submit" wrap="hard"
                      v-model="sendMessage.message"></textarea>
          </div>
          <div class="ui fluid labeled icon button send-message-btn" id="submit" @click="submit">
            <i class="paper plane outline icon"></i>
            发送
          </div>
        </div>
        <div class="ui form message-input-area" v-else>
          <h5 style="color: #e74000; font-weight: lighter">请先选择聊天好友</h5>
        </div>
      </div>
    </div>

    <!--友人帐区域-->
    <div class="box-shadow-max">
      <div class="ui top attached teal m-opacityFriendImg segment box-shadow-max">
        <div class="ui m-padded-tb-large m-container-mm">
          <div class="ui stackable m-container-mini m-opacityFriendImg grid">
            <!-- 父容器，用于设置flex布局和滚动 -->
            <div class="scrollable-friends"
                 style="display: flex;
                 overflow-x: auto;
                 -webkit-overflow-scrolling: touch; /* 为移动端提供更好的滚动体验 */
                 white-space: nowrap;width: 100%;">
              <!-- 最近记录显示区域 -->
              <div class="m-margin-tb-tiny four wide column" v-for="(friend, index) in friendList" :key="index"
                   style="padding-top: 0rem!important;
                   padding-bottom: 0rem!important;
                   flex-shrink: 0;
                   padding-right: 7px;
                   padding-left: 7px;"
                   @contextmenu.prevent="showDeleteBtn(index, $event)">
                <a href="#" class="class_outer"
                   @click='showChat(friend.usernameTa, friend.avatarTa, friend.nicknameTa)'>
                  <div align="center">
                    <div class="friends-link">
                      <img :src="friend.avatarTa" alt=""
                           class="friends-link-image" style="opacity: 1">
                      <div class="m-margin-top">
                        <h4 class="m-font-size-text-friends m-margin-tb-tiny">
                          {{friend.nicknameTa}}:&nbsp;
                          <span v-if="friend.chat.content.length > 5">{{friend.chat.content.slice(0, 5)}}...</span>
                          <span v-else>{{friend.chat.content}}</span>
                        </h4>
                      </div>
                    </div>
                  </div>
                </a>
                <!-- 动态显示的删除按钮 -->
                <transition name="fade">
                  <div v-if="deleteRecord.deleteIndex == index" class="delete-button"
                       @click="deleteFriendRecord(friend.usernameTa, index)">
                    删除记录
                  </div>
                </transition>
              </div>
              <!--/*-->
              <div class="m-margin-tb-tiny four wide column" th:each="friendlink : ${friendlinks}"
                   style="padding-top: 0rem!important; padding-bottom: 0rem!important;">
                <a href="#" class="class_outer" th:href="@{${friendlink.blogaddress}}">
                  <div align="center">
                    <div class="friends-link">
                      <img src="../static/images/friend_record_3.jpg" th:src="@{${friendlink.pictureaddress}}" alt=""
                           class="friends-link-image" style="opacity: 1">
                      <div class="m-margin-top">
                        <h4 class="m-font-size-text-friends m-margin-tb-tiny" th:text="${friendlink.blogname}">
                          断背山</h4>
                        <span>(*´▽｀)ノノ</span>
                      </div>
                    </div>
                  </div>
                </a>
              </div>
              <!--*/-->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<br>

<!--确认删除-->
<div class="ui tiny modal">
  <i class="close icon"></i>
  <div class="header">
    记录删除
  </div>
  <div class="content">
    <div class="description" name="descriptionDel">
      确定要删除聊天记录嘛？关于Ta的所有记录将被删除不再找回！
    </div>
  </div>
  <div class="actions">
    <button class="ui secondary button" id="confirmDel">
      确认
    </button>
    <button class="ui cancel button" id="cancelDel">
      取消
    </button>
  </div>
</div>

<!--确认注销-->
<div th:fragment="destroyAccount" class="ui destroy modal">
  <i class="close icon"></i>
  <div class="header">
    账号注销
  </div>
  <div class="content">
    <div class="ui form warning">
      <div class="field">
        <label>确认密码</label>
        <input type="password" name="password" placeholder="请输入密码...">
      </div>
      <div class="ui warning message">
        <div class="header">注销提醒！</div>
        <ul class="list">
          <li>只有填入你的账号密码, 你才能注销帐号</li>
          <li>注销账号, 意味着你的账号信息全部清空</li>
        </ul>
      </div>
    </div>
  </div>
  <div class="actions">
    <button class="ui secondary button" id="confirmDestroy">
      确认
    </button>
    <button class="ui cancel button">
      取消
    </button>
  </div>
</div>

<!--暂存信息-->
<input type="hidden" name="friendName" th:value="${toFriend?.username}"/>
<input type="hidden" name="friendAvatar" th:value="${toFriend?.avatar}"/>
<input type="hidden" name="friendNickname" th:value="${toFriend?.nickname}"/>

<script src="../static/js/vue.js" th:src="@{/js/vue.js}"></script>
<script src="../static/js/axios-0.18.0.js" th:src="@{/js/axios-0.18.0.js}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
<!--第一种多人物的看板娘，缓存慢-->
<!--<script src="https://fastly.jsdelivr.net/gh/stevenjoezhang/live2d-widget/autoload.js"></script>-->

<script>

    $('.ui.dropdown').dropdown({
        on: 'hover'
    });

    $('.menu.toggle').click(function () {
        $('.m-item').toggleClass('m-mobile-hide');
    });

    function deleteAccount() {
        $('.destroy.modal').modal('show');

        $('#confirmDestroy').click(async () => {
            var searchParams = new URLSearchParams();
            searchParams.append("password", $("[name='password']").val());

            const response = await fetch("/dev/login/delete", {
                method: 'POST',
                redirect: 'follow', // 允许fetch跟随重定向
                body: searchParams
            });
            const data = await response.json();
            console.log(data)
            if (data.status === "error") {
                alert(data.message);
                window.location.href = data.redirectUrl;
            } else if (data.status === "success") {
                alert(data.message);
                // 重定向到指定URL
                window.location.href = data.redirectUrl;
            }
        })
    }

    // const cUser = '<%= session.getAttribute("user") %>'; // 在JSP中才有用
    const cUsername = $("[name='concurrentUsername']").val();

    const toFriendName = $("[name='friendName']").val();
    const toFriendAvatar = $("[name='friendAvatar']").val();
    const toFriendNickname = $("[name='friendNickname']").val();

    let ws;
    new Vue({
        el: "#app",
        data() {
            return {
                isShowChat: false,
                chatMes: false,
                isOnline: true,
                username: cUsername,
                toName: "",
                toNickname: "",
                toAvatar: "",
                toId: 0,
                clickNum: 0,
                deleteRecord: {
                    deleteIndex: -1, // 存储当前要删除朋友的索引
                    deleteX: 0,
                    deleteY: 0
                },
                sendMessage: { // fromName、sendTime等在服务端获取
                    toName: "",
                    message: "",
                    sendTime: null
                },
                inputMessage: "",
                historyMessage: [
                    /*{toName: "李四", message: "你好,张三", sendTime: ""},
                    {toName: "李四", message: "在吗", sendTime: ""},
                    {toName: "李四", message: "怎么不说话", sendTime: ""}, // 我发的
                    {fromName: "张三", message: "你好,李四", sendTime: ""} // 对面发的*/
                ],
                // 存放最近聊天记录
                friendList: [ // 需要存(用户名、用户别名、头像地址、聊天记录...)
                    {
                        usernameTa: "",
                        avatarTa: "",
                        nicknameTa: "",
                        chat: {
                            id: 1,
                            sendTime: "",
                            senderUsername: "",
                            recipientUsername: "",
                            content: "",
                            type: false,
                            isRead: true
                        }
                    }
                ],
                systemMessages: [
                    /*"张三",
                    "李四"*/
                ]
            }
        },
        created() {
            this.init();
            this.showChat(toFriendName, toFriendAvatar, toFriendNickname);
        },
        /*mounted() {
            this.fetchFriendList();
        },*/
        methods: {
            async init() {
                await this.fetchFriendList();

                // 创建webSocket对象(这里要加上dev)
                ws = new WebSocket("ws://localhost:8080/dev/chat");

                // 给ws绑定事件
                ws.onopen = this.onopen;

                // 接收到服务端推送的消息后触发
                ws.onmessage = this.onMessage;

                ws.onclose = this.onClose;
            },
            // 触发showChat时向后端发起请求, 将返回结果按需存入sessionStorage(请求当前登录用户和friendName的聊天记录)
            async showChat(friendName, friendAvatar, friendNickname) {
                if (friendName == "" || friendName == null || friendName == undefined) {
                    console.log("无效username");
                    return;
                }

                // 拿到friendName用户的id
                await axios.get("friendId/" + friendName).then(res => {
                    this.toId = res.data;
                });

                this.toName = friendName;
                this.toAvatar = friendAvatar;
                this.toNickname = friendNickname;

                // 根据toName获取聊天历史记录(sessionStorage以键值对存储数据于浏览器)
                let history = sessionStorage.getItem(this.toName); // 如果sessionStorage中没有存储关于toName的历史记录会返回null
                if (!history) {
                    await axios.get("record/" + this.toName).then(res => {
                        this.historyMessage = res.data;
                    });
                } else {
                    // 将Json字符串转为JavaScript对象
                    this.historyMessage = JSON.parse(history);
                }
                // 输入置空
                this.sendMessage.message = "";
                // 展示聊天对话框
                this.isShowChat = true;
                // 显示“消息发送区域”
                this.chatMes = true;
            },
            submit() { // 触发submit时，在后台将sendMessage存入List集合，根据一定策略存入数据库(算了，简单点吧)
                if (this.sendMessage.message == "" || this.sendMessage.message == "\n") {
                    this.sendMessage.message = "";
                    alert("消息不能为空哦~");
                    return;
                }
                if (this.toName == "") {
                    alert("请先选择发送对象哦~");
                    return;
                }

                this.sendMessage.toName = this.toName;
                // 发送前先格式化时间
                var formattedTime = new Intl.DateTimeFormat('zh-CN', {
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit'
                }).format(new Date());
                this.sendMessage.sendTime = formattedTime;

                // stringify将JavaScript对象转为Json字符串格式
                this.historyMessage.push(JSON.parse(JSON.stringify(this.sendMessage))); // push之后会自动重新渲染聊天界面
                sessionStorage.setItem(this.toName, JSON.stringify(this.historyMessage));
                // 发送时就是Date对象
                this.sendMessage.sendTime = new Date();
                // 发送消息
                ws.send(JSON.stringify(this.sendMessage));
                // 更新friendList(这里是发送者)
                this.updateFriendList(this.toName, this.sendMessage.message);
                // 发完置空
                this.sendMessage.message = "";
            },
            async fetchFriendList() {
                // 拿到当前登录用户的最近聊天记录列表
                await axios.get("record").then(res => {
                    this.friendList = res.data;
                    console.log(this.friendList)
                    this.$nextTick(() => {
                        // 视图现在应该已经更新了
                    });
                });
            },
            updateFriendList(username, message) {
                let index = this.friendList.findIndex(friend => friend.usernameTa === username);
                if (index >= 0) {
                    this.$set(this.friendList[index].chat, 'content', message);
                    let newFriend = this.friendList.splice(index, 1)[0]; // 移除并获取下标为index的元素
                    // 将该元素插入到数组的第一个位置
                    this.friendList.unshift(newFriend);
                } else {
                    // this.fetchFriendList(); // 执行在FriendMapper.isFriendByName和ChatMapper.saveChat前(...未知...)
                    // 如果friendList里面没有username的记录，则username一定来源于toFriendName
                    let newFriend = {
                        usernameTa: toFriendName,
                        avatarTa: toFriendAvatar,
                        nicknameTa: toFriendNickname,
                        chat: {
                            id: null,
                            sendTime: new Date(),
                            senderUsername: this.username, // 当前用户
                            recipientUsername: username, // toFriendName
                            content: message,
                            type: false,
                            isRead: true
                        }
                    }
                    // 将该元素插入到数组的第一个位置
                    this.friendList.unshift(newFriend);
                }
            },
            // 显示friendIndex的删除键
            showDeleteBtn(friendIndex, event) {
                if (this.deleteRecord.deleteIndex != -1) this.deleteRecord.deleteIndex = -1;
                else this.deleteRecord.deleteIndex = friendIndex;
                // this.deleteRecord.deleteX = event.clientX - rect.width / 2;
                // this.deleteRecord.deleteY = event.clientY - rect.height / 2;
            },
            // 删除friendIndex聊天记录
            async deleteFriendRecord(username, index) {
                $('.tiny.modal').modal('show');

                $('#confirmDel').click(async () => {
                    try {
                        // await axios.delete("delete/" + username); // 会以等差数列递增删除(严重bug)
                        this.friendList.splice(index, 1); // 从数组中删除对应的朋友数据
                        console.log(this.friendList);
                        this.deleteRecord.deleteIndex = -1; // 隐藏删除按钮
                        $('.tiny.modal').modal('hide');
                    } catch (error) {
                        // 处理删除失败的情况
                        console.error('删除失败:', error);
                    }
                });

                $('#cancelDel').click(() => {
                    $('.tiny.modal').modal('hide');
                    // 这里不需要特殊处理，因为没有执行删除逻辑
                });
            },
            // 连接成功建立的回调方法
            onOpen() {
                console.log("进入open");
                this.isOnline = true;
            },
            // 连接关闭的回调方法
            onClose() {
                console.log("进入close");
                sessionStorage.clear(); // 退出就置空，下次从数据库读出来
                this.isOnline = false;
            },
            // 接收到消息的回调方法(ps：要接收方登录在线才会回调, 并且也是对方客户端回调)
            onMessage(evt) {
                // 获取服务端推送过来的消息
                var dataStr = evt.data;
                // 将dataStr转换为Json对象(即JavaScript中的Json对象)
                var res = JSON.parse(dataStr);
                console.log(res); // 时间会变成时间戳

                // 更新friendList(这里是接收者)
                this.updateFriendList(res.fromName, res.message);

                // 判断是否是系统消息
                if (res.system) {
                    // 系统消息  好友列表展示(暂时用不到)
                    /*var names = res.message;
                    this.friendList = [];
                    this.systemMessages = [];
                    console.log("当前对象：" + this.username);
                    for (let i = 0; i < names.length; i++) {
                        if (names[i] != this.username) {
                            this.friendList.push(names[i]);
                            this.systemMessages.push(names[i]);
                        }
                    }*/
                } else { // 非系统消息
                    // 将时间戳转化为"MM-dd HH:mm"格式
                    var date = new Date(res.sendTime);
                    var formattedTime = new Intl.DateTimeFormat('zh-CN', {
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    }).format(date);
                    res.sendTime = formattedTime;

                    var history = sessionStorage.getItem(res.fromName);
                    if (!history) {
                        this.historyMessage = [res];
                    } else {
                        this.historyMessage.push(res);
                    }
                    sessionStorage.setItem(res.fromName, JSON.stringify(this.historyMessage));
                }
            }
        }
    });

    // 绑定退出按钮的点击事件
    $('#logout-link').on('click', function (event) {
        // 清除 sessionStorage
        window.sessionStorage.clear();
    });

</script>
</body>
</html>